<?php
namespace Duobao\Controller;

use \Think\Model;
use Duobao\Model\UserModel as User;
use Com\Sms\Sms as Sms;
use Think\MyVerify as MyVerify;
use Com\Weixin\Pay\unit\JsApiPay as JsApiPay;
use Duobao\Controller\LogController as MyLog;
use Org\Util\JWT as JWT;

class UserController extends ControllerBase{

    /**
     * 默认
     */
    public function index()
    {
        echo "<!--hi , i'm from " . MODULE_NAME . "~" . APP_STATUS, "-->";
    }

    /**
     * 用户登陆
     */
    public function Login(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $username = I('post.phone');
            $password = I('post.password');

            if(empty($username) || empty($password)){
                $ret['status'] = 403;
                $ret['msg'] = "请求的用户帐户或用户密码为空";
            }else{
                $model = new User();
                $restult = $model->Login($username,$password);

                if($restult['status'] == 'ok'){
                    $ret['data']['status'] = $restult['status'];
                    $ret['data']['token'] = $restult['token'];
                }else{
                    $ret['data'] = "用户名或密码错误";
                }
            }
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     *微信登陆(公众号登陆)
     */
    public function wxLogin(){
        $jsApi = new JsApiPay();
        $openId = $jsApi->GetOpenid();
        #计算长度
        if(!count($openId) == 28){
            MyLog::write($openId);
        }else{
            #获取union_id,（取消获取，修改逻辑为，可能存在两个公众号，用户关注事件，判断用户的union_id是否存在，如果不存在插入，存在更新）
            #MyLog::write($openId);
//            $model = M('user');
//            $condition['openid'] = $openId;
//            #$unionId = $model->where($condition)->getField("union_id");
//            $id = $model->where($condition)->getField('id');
//            $member = M('member');
//            $condition2['weixin_id'] = $id;
//            $uid = $member->where($condition2)->getField('uid');
            $model = M('openid');
            $condition['openid'] = $openId;
            $condition['wx_hao'] = C('wx_hao');
            $exist = $model->where($condition)->find();
            #MyLog::write($uid);
            #判断如果uid不存在，调用weixinController,中的插入用户函数
            if($exist['uid']){
                $token = JWT::encode($exist['uid'].':'.time(),C("SECRET_KEY"),"HS256");
                #MyLog::write($token);
            }else{
                $uid =  R('Weixin/insertUser',array($openId));
                $token = JWT::encode($uid.':'.time(),C("SECRET_KEY"),"HS256");
                MyLog::write('2'.$token);
            }
            $act=I('get.act');
            #MyLog::write($act);
            $url = C("FRONT_URL").'?token='.$token."&c=".$act;
            #MyLog::write($url);
            header('Location:'.$url);
        }
    }

    /**
     * 用户微信登陆 version 2
     */
    public function wxLogin2(){
        $jsApi = new JsApiPay();
        $openId = $jsApi->GetOpenid();
        #计算长度
        if(!count($openId) == 28){
            MyLog::write($openId);
        }else {
            $model = M('openid');
            $condition['openid'] = $openId;
            $condition['wx_hao'] = C('wx_hao');
            $exist = $model->where($condition)->find();
            if($exist['uid']){
                $token = JWT::encode($exist['uid'].':'.time(),C("SECRET_KEY"),"HS256");
                #MyLog::write($token);
            }else{
                $uid =  R('Weixin/insertUser2',array($openId));
                $token = JWT::encode($uid.':'.time(),C("SECRET_KEY"),"HS256");
                MyLog::write('2'.$token);
            }
            $act=I('get.act');
            #MyLog::write($act);

            $url = C("FRONT_URL").'?token='.$token."&c=".$act;
            #MyLog::write($url);
            header('Location:'.$url);
        }
    }

    /**
     * 用户注册
     * 注册流程，用户输入图形验证码，
     *
     */
    public function Register(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $phone = I('post.phone');
            $password = I('post.password');
            $msgcode = I('post.msgcode');

            #判断用户填写的手机验证码和用户手机号是否对应
            #获取数据库message表中给当前phone发送的最后一条记录


            if(!empty($phone)){
                if(!empty($password)){
                    if(!empty($msgcode)){
                        $model = new User();
                        $result = $model->Register($phone,$password,$msgcode);
                        if($result>1){
                            $ret['data']['status'] = 'ok';
                        }else{
                            $ret['data']['status']= 'error';
                            $ret['data']['error_msg']= $result;
                        }
                    }else{
                        $ret['data']['msg'] = 'message code is empty';
                    }
                }else{
                    $ret['data']['msg'] .='password is empty';
                }
            }else{
                $ret['data']['msg'] = 'phone number is empty';

            }
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     * 使用tp的验证码功能
     */
    public function verify(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $verify = new MyVerify();
            $result = $verify->entry();
            $ret['data'] = $result;
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['status'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /* end of User Controller */

    /**
     * 用户注册是手机验证码的发送
     * 发送大短信给注册的用户的手机
     * 需要限制没小时只能发送5条，每个ip
     * 接收参数：前端发送过来的用户的手机号，和验证码
     * 首先判断验证码是否正确
     */
    public function sendMsgForRegPhone(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $code = I('post.code');
            $phone = I('post.phone');
            $mark = I('post.mark');
            #MyLog::write($phone);
//            $ret['data']['code'] = $code;
//            $ret['data']['phone'] = $phone;
            #获取用户输入的数据，转换为大写
            $mark = $this->getCode($mark);#获取用户输入的编码
            if($mark){
                $code = strtoupper($code);
                #MyLog::write($mark);
                if($mark == $code){
                    #输入的验证码正确
                    #判断用户输入手机号码是否符合规范
                    if($this->isPhone($phone)){
                        #判断手机号码是否在数据库中存在
                        if(!$this->dbExistPhone($phone)){
                            #发送短信验证码，并记录短信发送日志
                           $sendRet =  $this->sendMsg($phone);
                            if($sendRet){
                                $ret['data'] = $sendRet;
                                $ret['msg'] ='短信发送成功';
                            }else{
                                $ret['data'] = '短信系统发送失败';
                            }
                        }else{
                            $ret['status'] = 403;
                            $ret['msg'] = '手机号码已存在';
                        }
                    }else{
                        $ret['status'] = 403;
                        $ret['msg'] = '手机号码格式不正确';
                    }
                }else{
                    $ret['status'] = 403;
                    $ret['msg'] = '验证码输入错误';
                }
            }else{
                $ret['msg'] = '验证码超时';
                $ret['status'] = 403;
            }

        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     * 验证手机号码填写的是否正确
     * 获取的是手机号码
     * 返回的手机号的是否正确
     */
    private function isPhone($phone){
        #判断用户输入的手机号是否符合规范
        if (!is_numeric($phone)) {
            return false;
        }

        return  preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $phone) ? true : false;
    }

    /**
     * 判断当前的用户的手机在数据库中是否已经存在
     */
    private function dbExistPhone($phone){
        $model = new \Think\Model();
        $where['mobile'] = $phone;
        $result = $model->table("__MEMBER__")->where($where)->find();
        #判断手机号码在数据库中是否已经存在
        #MyLog::write($model->getLastSql());
        if($result) {
            return true;
        }else{
            return false;
        }

    }

    /**
     * 对用户的ip进行限制，防止用户无限的点击发送验证码
     */
    private function sendMsg($phone){
        $model = new \Think\Model();
        $ip = $_SERVER['REMOTE_ADDR'];
        #判断当前的手机号码在同一ip上的没小时最多请求5次
        $count = $model->query("select count(*) as mycount from __PREFIX__message WHERE `ip` ='$ip' and phone='$phone' and time > ".(time()-3600));

        if($count[0]['mycount'] > C('SMS_LIMIT')){
            E('同一个ip上的同一用户1小时内发送短信超过5次',403);
        }else{
            $checkCode = rand(100000,999999);
            $messageStr = '您在'.C("APP_NAME").'的注册验证码：'.$checkCode.'，5分钟内有效。如非本人操作，可不理会！';
            #发送短信
            $sms = new Sms();
            $result = $sms->sendSMS($phone,$messageStr);
            $result = explode(',',$result);
            if($result[1] == 0){
                #记录发送日志到数据表中

                $data['ip'] = $ip;
                $data['phone'] = $phone;
                $data['time'] = strtotime($result[0]);
                $data['content'] = $messageStr;
                $data['uid'] = 0;#默认uid为0
                $data['code'] = $checkCode;
                $dbResult = $model ->table("__MESSAGE__")->add($data);
                #判断数据库的是否录入
                if(!$dbResult){
                    MyLog::write('短信的记录日志错误');
                }

                return true;#返回true表示发送成功
            }else{
                #记录发送日志
                MyLog::write($result);
                return false;#返回false，表示发送失败

            }
        }


    }

    /**
     * 处理用户输入信息到公众号和处理用户关注公众号后添加商品的url的功能
     * 前置条件：数据库中配置wx_welcome_url中携带参数
     */
    public function handle_winxin_output_url(){
        #用户认证
        $jsApi = new JsApiPay();
        $openId = $jsApi->GetOpenid();

        $model = M('openid');
        $condition['openid'] = $openId;
        $uid = $model->where($condition)->getField('uid');

        #获取商品的id
        $goods_sid = I('get.sid');
        $controller = 'detail';
        #根据商品的sid获取商品的种类商品的中正在出售的商品的id
        $model = new \Think\Model();
        $goods_id = $model->query("select `id` from __PREFIX__shoplist WHERE `sid` =$goods_sid ORDER BY `id` DESC limit 1")[0]['id'];
        if($uid){
            $token = JWT::encode($uid.':'.time(),C("SECRET_KEY"),"HS256");
            $url = C("FRONT_URL").'?token='.$token."&c=".$controller."&id=".$goods_id;
            header('Location:'.$url);
        }else{
            MyLog::write(C('APP_NAME').":在点击关注回复的商品的时候获取用户id失败 usercontroller line:".__LINE__);
            #兼容处理，让用户直接访问前端的商品连接
            $url = C("FRONT_URL")."?c=".$controller."&id=".$goods_id;
            header('Location:'.$url);
        }
    }
}
